package cn.iocoder.yudao.module.reading.controller.admin.book;

import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.reading.controller.admin.book.vo.*;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.service.book.AdminPictureBookService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 管理后台 - 绘本管理
 *
 * @author 芋道源码
 */
@Tag(name = "管理后台 - 绘本管理")
@RestController
@RequestMapping("/reading/admin/books")
@Validated
@Slf4j
public class AdminPictureBookController {

    @Resource
    private AdminPictureBookService adminPictureBookService;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    /**
     * 检查当前用户是否为管理员
     * 绘本管理只允许管理员操作
     */
    private void checkAdminPermission() {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        if (loginUser == null) {
            throw new ServiceException(401, "用户未登录");
        }
        if (!UserTypeEnum.ADMIN.getValue().equals(loginUser.getUserType())) {
            throw new ServiceException(403, "权限不足，只有管理员可以管理绘本");
        }
    }

    @PostMapping("/create")
    @Operation(summary = "创建绘本")
    @PreAuthenticated
    public CommonResult<Long> createPictureBook(@Valid @RequestBody PictureBookCreateReqVO createReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("创建绘本，标题: {}, 绘本集ID: {}", createReqVO.getTitle(), createReqVO.getBookSetId());

        Long bookId = adminPictureBookService.createPictureBook(createReqVO);

        log.info("绘本创建成功，ID: {}", bookId);
        return success(bookId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新绘本")
    @PreAuthenticated
    public CommonResult<Boolean> updatePictureBook(@Valid @RequestBody PictureBookUpdateReqVO updateReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("更新绘本，ID: {}, 标题: {}", updateReqVO.getId(), updateReqVO.getTitle());

        adminPictureBookService.updatePictureBook(updateReqVO);

        log.info("绘本更新成功，ID: {}", updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除绘本")
    @PreAuthenticated
    public CommonResult<Boolean> deletePictureBook(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("删除绘本，ID: {}", id);

        adminPictureBookService.deletePictureBook(id);

        log.info("绘本删除成功，ID: {}", id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得绘本")
    @Parameter(name = "id", description = "绘本编号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<PictureBookAdminRespVO> getPictureBook(@RequestParam("id") Long id) {
        // 检查管理员权限
        checkAdminPermission();

        PictureBookDO book = adminPictureBookService.getPictureBook(id);
        PictureBookAdminRespVO result = BeanUtils.toBean(book, PictureBookAdminRespVO.class);

        // 转换封面URL为完整URL
        if (result.getCover() != null) {
            result.setCover(staticResourceUrlUtils.toFullUrl(result.getCover()));
        }

        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得绘本分页")
    @PreAuthenticated
    public CommonResult<PageResult<PictureBookAdminRespVO>> getPictureBookPage(@Valid PictureBookPageReqVO pageReqVO) {
        // 检查管理员权限
        checkAdminPermission();

        PageResult<PictureBookDO> pageResult = adminPictureBookService.getPictureBookPage(pageReqVO);
        PageResult<PictureBookAdminRespVO> result = BeanUtils.toBean(pageResult, PictureBookAdminRespVO.class, respVO -> {
            // 转换封面URL为完整URL
            if (respVO.getCover() != null) {
                respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
            }
        });
        return success(result);
    }

    @GetMapping("/list-by-book-set")
    @Operation(summary = "根据绘本集ID获取绘本列表")
    @Parameter(name = "bookSetId", description = "绘本集编号", required = true, example = "1")
    @PreAuthenticated
    public CommonResult<List<PictureBookAdminRespVO>> getPictureBooksByBookSetId(@RequestParam("bookSetId") Long bookSetId) {
        // 检查管理员权限
        checkAdminPermission();

        List<PictureBookDO> books = adminPictureBookService.getPictureBooksByBookSetId(bookSetId);
        List<PictureBookAdminRespVO> result = BeanUtils.toBean(books, PictureBookAdminRespVO.class, respVO -> {
            // 转换封面URL为完整URL
            if (respVO.getCover() != null) {
                respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
            }
        });
        return success(result);
    }

    @GetMapping("/list")
    @Operation(summary = "获得绘本列表")
    @PreAuthenticated
    public CommonResult<List<PictureBookAdminRespVO>> getPictureBookList(
            @Parameter(description = "绘本集ID") @RequestParam(value = "bookSetId", required = false) Long bookSetId,
            @Parameter(description = "标题") @RequestParam(value = "title", required = false) String title) {
        checkAdminPermission();

        List<PictureBookDO> list = adminPictureBookService.getPictureBookList(bookSetId, title);
        List<PictureBookAdminRespVO> result = BeanUtils.toBean(list, PictureBookAdminRespVO.class, respVO -> {
            // 转换封面URL为完整URL
            if (respVO.getCover() != null) {
                respVO.setCover(staticResourceUrlUtils.toFullUrl(respVO.getCover()));
            }
        });
        return success(result);
    }

    @PostMapping("/batch-create")
    @Operation(summary = "批量创建绘本")
    @PreAuthenticated
    public CommonResult<List<Long>> batchCreatePictureBooks(@Valid @RequestBody List<PictureBookCreateReqVO> createReqVOs) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("批量创建绘本，数量: {}", createReqVOs.size());

        List<Long> bookIds = adminPictureBookService.batchCreatePictureBooks(createReqVOs);

        log.info("批量创建绘本成功，IDs: {}", bookIds);
        return success(bookIds);
    }

    @GetMapping("/next-id")
    @Operation(summary = "获取下一个绘本ID")
    @PreAuthenticated
    public CommonResult<Long> getNextPictureBookId() {
        // 检查管理员权限
        checkAdminPermission();

        Long nextId = adminPictureBookService.getNextPictureBookId();
        return success(nextId);
    }

    @GetMapping("/batch-next-ids")
    @Operation(summary = "批量获取下一批绘本ID")
    @PreAuthenticated
    public CommonResult<List<Long>> getBatchNextPictureBookIds(@RequestParam("count") int count) {
        // 检查管理员权限
        checkAdminPermission();

        log.info("批量获取绘本ID，数量: {}", count);

        List<Long> idList = adminPictureBookService.getBatchNextPictureBookIds(count);

        log.info("批量获取绘本ID成功，数量: {}, ID列表: {}", count, idList);
        return success(idList);
    }

}
